package com.yuri.news.service.impl;

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.yuri.news.entity.Role;
import com.yuri.news.jpa.RoleRepository;
import com.yuri.news.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	RoleRepository roleRepository;
	@Override
	public Boolean addRole(Role role) {
		Boolean flag = false;
		List<Role> roles = null;
		// 查询是否已经存在此用户
		roles = roleRepository.findByRoleName(role.getRoleName());
		// 如果不存在 则保存
		if(!(roles != null && roles.size() > 0)) {
			role.setIsAvailable(true);
			roleRepository.save(role);
			flag = true;
		}
		return flag;
	}

	@Override
	public Page<Role> findRoleAll(Boolean isAva, Pageable page) {
		// TODO Auto-generated method stub
		return roleRepository.findByIsAvailable(isAva, page);
	}

	@Override
	public Role findRoleById(Long id) {
		Optional<Role> optional = roleRepository.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}else {
			return null;
		}
	}

	@Override
	public Boolean setRoleAvailable(Long id) {
		// TODO Auto-generated method stub
		Boolean flag = false;
		// 根据id查询此角色
		Role role = findRoleById(id);
		// 判断是否存在
		if(role != null) {
			// 根据现在状态修改角色状态
			if(role.getIsAvailable()) {
				role.setIsAvailable(false);
			}else {
				role.setIsAvailable(true);
			}
			// 保存角色
			roleRepository.save(role);
			flag = true;
		}
		return flag;
	}

	@Override
	public Page<Role> findRoleByKey(String key, Boolean isAva, Pageable page) {
		// TODO Auto-generated method stub
		Page<Role> roles = null;  // 存放查询后的数据
		
		// 如果key为“”则查询所有
		if ("".equals(key)) {
			return findRoleAll(isAva, page);
		} else {
			roles = roleRepository.findByRoleNameLikeAndIsAvailable("%"+key+"%", isAva, page);
		}
		
		return roles;
	}

}
